<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<style>
			.banner-images{display: flex; overflow: auto;}
			.banner-images img.td-img{max-width: 60px; margin:0 2px; border: 1px solid #333;}
			
			.edit-title{display: block; margin-bottom: 8px; font-weight: bold; border-bottom: 1px solid #D3D3D3; padding: 4px;}
			.edit-title i.fa{font-size: 12px; margin-left: 10px;}
			.edit-title i.fa:hover{opacity: 0.8;}
			.moduleInfo{box-sizing: border-box; height: 300px; display: flex;justify-content: center;}
			.moduleInfo .moduleInfo-images{display: inline-block; width: 350px; box-sizing: border-box; position: relative;}
			.moduleInfo .moduleInfo-images > img{width:300px}
			
			.moduleInfo .moduleInfo-text{display: inline-block; width: 400px; box-sizing: border-box; padding: 0px 15px;}
			.moduleInfo-text .form-item {margin-bottom: 20px;}
			.moduleInfo-text .form-item>label{min-width: 72px; display: inline-block; text-align: right;}
			
			.module-banners{height: 230px;}
			.module-banners > ul{display: flex; overflow: auto; text-align: center;}
			.module-banners > ul::after{content: ''; min-width: 6px; display: block; visibility: hidden;}
			.module-banners > ul >li{position: relative;height: 200px;box-shadow: 0 0 4px 0 #bbb;margin: 6px;}
			.module-banners > ul >li > img{height: 168px;min-height: 168px;}
			.module-banners > ul >li .module-banner-delete{position: absolute; top: 10px; right: 10px; color: #FF0000;}
			.module-banners > ul >li .module-banner-delete:hover{opacity: 0.8;}
			.presentCombo-img{width: 120px;margin-right: 10px;}
			
			.batchEditModuleForm label{text-align: right;}
			.batchEditModuleForm .form-item{text-align: center;}

			.editBannerLink{box-sizing:border-box;padding:6px 12px;width:100%;border-right:0;border-left:0; border-top: 1px solid #bbb; border-bottom: 0;min-width: 168px;}

			.daterangepicker{z-index: 10000;}

			#moduleEditWin > .super-theme-example{display: flex; height: 100%; width: 100%; flex-wrap: wrap;background: #fff;box-sizing: border-box;}
			#moduleEditWin > .super-theme-example > div{width: 50%;box-sizing: border-box; border-bottom: 1px solid #ccc;overflow-y: auto;overflow-x: hidden;}
			#moduleEditWin > .super-theme-example > div:last-child{width: 100%;}
			#moduleEditWin > .super-theme-example > div:nth-child(2n){border-left: 1px solid #ccc;}
		</style>
		<div class="super-theme-example">
			<div class="options-toolbar">	
				<form id="moduleDatagridQueryParams">
					<input class="easyui-textbox" name="collectionId" data-options="width:120,prompt:'模块ID...'">
					<input class="easyui-textbox" name="name" data-options="width:150,prompt:'模块名称...'">
					<input class="easyui-textbox" name="comments" data-options="width:150,prompt:'模块备注...'">
					<a href="javascript:void(0)" class="easyui-linkbutton primary" data-options="iconCls:'fa fa-search'" onclick="app_module.methods.queryDatagrid();">查询</a>
				</form>
				<div class="top-options">
					<a href="javascript:void(0)" class="easyui-menubutton info" data-options="menu:'#module_list_tools'">操作</a>
					<div id="module_list_tools" style="width:120px;">
						<div data-options="iconCls:'fa fa-plus'" onclick="app_module.methods.createModule();">新建</div>
						<div data-options="iconCls:'fa fa-copy'" onclick="app_module.methods.batchCopyMoudle();">批量复制</div>
						<div data-options="iconCls:'fa fa-edit'" onclick="app_module.methods.batchEditMoudle();">批量备注</div>
						<div class="menu-sep"></div>
						<div data-options="iconCls:'fa fa-trash-o'" onclick="app_module.methods.batchDeleteMoudle();">批量删除</div>
						<div class="menu-sep"></div>
						<div data-options="iconCls:'fa fa-image'" onclick="app_module.methods.batchCover();">批量蒙版</div>
					</div>
				</div>
			</div>
			<table id="module-datagrid"></table>
			<div id="moduleEditWin" class="easyui-window" title="模块" style="width:1000px;height:900px" data-options="closed:true,modal:true,minimizable:false,maximizable:false,maximized:true,tools:[{iconCls:'fa fa-save',handler:function(){app_module.methods.persitsModule();}}]">
				<div class="super-theme-example">
					<div class="moduleInfoBox">
						<span class="edit-title">信息</span>
						<div class="moduleInfo">
							<div class="moduleInfo-text">
								<form id="moduleEditForm">
									<input name="collectionId" type="hidden" />
									<div class="form-item" style="margin-top: 20px;">
										<label for="" class="label-top">名称：</label>
										<input name="name" class="easyui-textbox" style="width: 250px;" prompt="名称...">
									</div>
									<div class="form-item">
										<label for="" class="label-top">备注：</label>
										<input name="comments" class="easyui-textbox" data-options="multiline:true" style="width: 250px; height: 60px;" prompt="备注...">
									</div>
									<div class="form-item">
										<label for="" class="label-top">呈现方式：</label>
										<input id="presentIdCombo" name="presentId" style="width: 250px;">
									</div>
								</form>
							</div>
							<div class="moduleInfo-images">
								<img src="dists/super/images/present_holder.png" />
							</div>
						</div>
					</div>
					<div class="moduleBannerBox">
						<span class="edit-title">banner<a class="module-banner-add"><i class="fa fa-plus"></i></a><a class="module-banner-add-empty" style="float:right">添加空banner</a></span>
						<div class="module-banners" style="height: 250px;">
							<ul></ul>
							<button type="button" id="moduleBannerUpload" style="display: none;"></button>
						</div>
					</div>
					<div class="moduleProductBox">
						<span class="edit-title">绑定产品<a class="module-product-add"><i class="fa fa-plus"></i></a><a class="module-product-add-aff" style="float:right">绑定产品By监测</a></span>
						<table id="module-banners-datagrid" style="height: 600px;"></table>
					</div>
				</div>
			</div>
			
			
			<div id="moduleAddProductWin" class="easyui-window" title="绑定产品" style="width:1000px;height:700px" data-options="closed:true,modal:true,minimizable:false,maximizable:false,tools:[{iconCls:'fa fa-save',handler:function(){app_module.methods.persitsModuleProduct();}}]">
				<div class="super-theme-example">
					<div class="options-toolbar">
						<form id="moduleProductDatagridQueryParams">
							<input class="easyui-textbox" name="productId" data-options="width:120,prompt:'商品ID'">
							<input class="easyui-textbox" name="tags" data-options="width:150,prompt:'商品标签'">
							<input class="easyui-textbox" name="comments" data-options="width:150,prompt:'商品备注'">
							<input class="easyui-textbox" name="productTitle" data-options="width:150,prompt:'商品名称'">
							<select id="sourceTypeCombo" class="easyui-combobox" name="sourceType" style="width:150px;">
							    <option value="">全部来源</option>
							    <option value="tmall">TMALL</option>
							    <option value="taobao">TAOBAO</option>
							    <option value="1688">1688</option>
							    <option value="other">其他</option>
							</select>
							<select id="moduleAddProductCategoryId" name="categoryId" class="easyui-combobox" style="width: 150px;"></select>
							<a href="javascript:void(0)" class="easyui-linkbutton primary" data-options="iconCls:'fa fa-search'" onclick="var queryParams = $('#moduleProductDatagridQueryParams').serializeJson(); if(queryParams.productId) queryParams.productId = queryParams.productId.replace(/[\r\n，]/g,','); $('#moduleProductDatagrid').datagrid('load',queryParams);">查询</a>
						</form>
					</div>
					<table id="moduleProductDatagrid"></table>
				</div>
			</div>

			<div id="moduleAddProductAffWin" class="easyui-window" title="绑定产品-监测条件" style="width:1000px;height:700px" data-options="closed:true,modal:true,minimizable:false,maximizable:false,tools:[{iconCls:'fa fa-save',handler:function(){app_module.methods.persitsModuleProductAff();}}]">
				<div class="super-theme-example">
					<div class="options-toolbar">
						<form id="moduleProductAffDatagridQueryParams">
							<input id="module-list-monitor-datepicker" class="datepicker-input" />
							<a href="javascript:void(0)" class="easyui-linkbutton primary" data-options="iconCls:'fa fa-search'" onclick="$('#moduleProductAffDatagrid').datagrid('load',app_module.methods.getModuleProductAffDatagrQueryParams());">查询</a>
						</form>
					</div>
					<table id="moduleProductAffDatagrid"></table>
				</div>
			</div>

			<div id="modulesBatchParame" class="easyui-dialog" title="批量编辑" style="width:500px;height:200px;padding: 10px;" data-options="modal:true,shadow:true,closed:true,buttons: [{
				text:'确定',
				handler: function(){
					app_module.methods.saveBatchEditParame()
				}
			},{
				text:'取消',
				handler:function(){
					$('#modulesBatchParame').dialog('close');
				}
			}]">
				<form class="batchEditModuleForm">
					<div class="form-item">
						<label for="comments">备注：</label>
						<input name="comments" class="easyui-textbox" data-options="prompt:'请输入备注...',type:'text'" style="width: 350px;"><br/><br/>
					</div>
				</form>
			</div>
			
		</div>
		<script src="dists/super/js/ddsort.js"></script>
		<script type="text/javascript" src="dists/plupload-2.3.6/js/plupload.full.min.js"></script>
		<script type="text/javascript" src="dists/plupload-2.3.6/js/i18n/zh_CN.js"></script>
		<script type="text/javascript">
			var app_module = {
				datas : {} , 
				methods : {
					initDatagrid : function(){
						$('#module-datagrid').datagrid({
							height: $(document).height() - 200,
						    url: commonConfig.shopUrlPrefix() + '/colletion',
						    columns:[[
						    	{field:'ck',checkbox:true,align:'center'},
								{field:'collectionId',title:'模块ID',width:50,align:'center'},
								{field:'name',title:'模块名称',width:100,align:'center'},
								{field:'comments',title:'模块备注',width:120,align:'center'},
								{field:'thumb',title:'呈现方式',width:80,align:'center',formatter: function(value,row,index){
									   return '<div><img class="td-img" src="'+ value +'"></div>';
								}},
								{field:'coverImg',title:'覆盖层',width:80,align:'center',formatter: function(value,row,index){
									   return '<div onclick="app_module.methods.uploadModuleCoverImg('+ row.collectionId +')">' +  (value ? '<img class="td-img" src="'+ value +'">' : '--') + '</div>';
								}},
								{field:'banners',title:'banners',width:80,align:'center',formatter: function(value,row,index){
									if(!value || value.length == 0) return '无' ;
									
									var _html = '' ; 
									var _values = value.split(';');
									$.each(_values, function(index , _value) {
										if(_value && _value.length > 0){
											_html += '<img class="td-img" src="'+ _value.split('@#@')[0] +'">';
										}
									});
									if(_html == '') return '无';
									 return '<div class="banner-images">'+_html+'</div>';
								}},
								{field:'productCount',title:'产品数量',width:50,align:'center'},
								{field:'options',title:'操作',width:150,align:'center',formatter: function(value,row,index){
									   return '<button class="row-btn info" onclick="app_module.methods.editModule('+row.collectionId+');">编辑</button>'+
									   		  '<button class="row-btn primary" onclick="app_module.methods.deleteModule('+row.collectionId+');">删除</button>'+
									   		  '<button class="row-btn success" onclick="app_module.methods.copyModule('+row.collectionId+');">复制</button>';
								}}
								
						    ]]
						});
					},
					uploadModuleCoverImg: function(collectionId){
						app_module.datas.coverModuleId = collectionId ; 
						app_module.datas.uploaderUploadCallBack = app_module.methods.uploadModuleCoverImgCallBack;
						$('#moduleBannerUpload').trigger('click');
					},
					uploadModuleCoverImgCallBack:function(result){
						var imgUrl = JSON.parse(result.response).datas[0];
						var _params = {
							collectionId: app_module.datas.coverModuleId,
							coverImg: imgUrl
						};
						requestBodyServer(commonConfig.shopUrlPrefix() + '/colletion/coverImg', 'PUT', _params).then((response) => {
							if (response.code == 1) {
								app_module.methods.queryDatagrid();
							}else {
								$.messager.alert('提示',response.message,'error');
							}
						}).catch((error) => {
							console.log(error)
						});
					},
					openCreateModuleWindow: function(){
						$('#moduleEditWin').window('open');
						$('#moduleEditForm').form('clear');
						
						$('#module-banners-datagrid').datagrid({
							toolbar: [{
								text: '解除绑定',
								iconCls: 'fa fa-close',
								handler: function(){
									var _checkRows = $('#module-banners-datagrid').datagrid('getChecked');
									if(_checkRows.length > 0){
										
										var _selectRows = [];
										$.each(_checkRows, function(index , _checkRow) {
											_selectRows.push(_checkRow);
										});
										$.each(_selectRows, function(index , _selectRow) {
											var _rowIndex = $('#module-banners-datagrid').datagrid('getRowIndex' , _selectRow);
											$('#module-banners-datagrid').datagrid('deleteRow' , _rowIndex);
										});
										$('#module-banners-datagrid').datagrid('enableDnd');
									}else{
										$.messager.alert('提示','没有选择数据...','warning');										
									}
								}
							},{
								text: '置顶',
								iconCls: 'fa fa-arrow-up',
								handler: function(){
									var _checkRows = $('#module-banners-datagrid').datagrid('getChecked');
									if(_checkRows.length > 0){
										var _selectRows = [];
										$.each(_checkRows, function(index , _checkRow) {
											_selectRows.push(_checkRow);
										});
										$.each(_selectRows, function(index , _selectRow) {
											var _rowIndex = $('#module-banners-datagrid').datagrid('getRowIndex' , _selectRow);
											$('#module-banners-datagrid').datagrid('deleteRow' , _rowIndex);
										});
										$.each(_selectRows, function(index , _selectRow) {
											$('#module-banners-datagrid').datagrid('insertRow' , {index : index , row : _selectRow});
										});
										
										$('#module-banners-datagrid').datagrid('enableDnd');
									}else{
										$.messager.alert('提示','没有选择数据...','warning');										
									}
								}
							},{
								text: '置底',
								iconCls: 'fa fa-arrow-down',
								handler: function(){
									var _checkRows = $('#module-banners-datagrid').datagrid('getChecked');
									if(_checkRows.length > 0){
										var _selectRows = [];
										$.each(_checkRows, function(index , _checkRow) {
											_selectRows.push(_checkRow);
										});
										$.each(_selectRows, function(index , _selectRow) {
											var _rowIndex = $('#module-banners-datagrid').datagrid('getRowIndex' , _selectRow);
											$('#module-banners-datagrid').datagrid('deleteRow' , _rowIndex);
										});
										$.each(_selectRows, function(index , _selectRow) {
											$('#module-banners-datagrid').datagrid('appendRow' , _selectRow);
										});
										
										$('#module-banners-datagrid').datagrid('enableDnd');
									}else{
										$.messager.alert('提示','没有选择数据...','warning');										
									}
								}
							},{
								text: '位置',
								iconCls: 'fa fa-exchange',
								handler: function(){
									var _checkRows = $('#module-banners-datagrid').datagrid('getChecked');
									if(_checkRows.length > 0){
										$.messager.prompt('提示', '调整位置:', function(r){
											var _number = Number(r);
											if (r && !isNaN(_number)){
												var _selectRows = [];
												$.each(_checkRows, function(index , _checkRow) {
													_selectRows.push(_checkRow);
												});
												$.each(_selectRows, function(index , _selectRow) {
													var _rowIndex = $('#module-banners-datagrid').datagrid('getRowIndex' , _selectRow);
													$('#module-banners-datagrid').datagrid('deleteRow' , _rowIndex);
												});
												$.each(_selectRows, function(index , _selectRow) {
													$('#module-banners-datagrid').datagrid('insertRow' , {index : (index + _number) , row : _selectRow});
												});
												
												$('#module-banners-datagrid').datagrid('enableDnd');
											}else{
												$.messager.alert('提示','输入的不是数字...','warning');	
											}
										});
									}else{
										$.messager.alert('提示','没有选择数据...','warning');										
									}
								}
							},{
								text: '随机打乱',
								iconCls: 'fa fa-magic',
								handler: function(){
									var data = $('#module-banners-datagrid').datagrid("getData")
									$('#module-banners-datagrid').datagrid("loadData", {datas: tools.shuffle(data.rows)});
								}
							}],
							pagination:false,
							idField: 'id',
						    columns:[[
						    	{field:'ck',checkbox:true,align:'center'},
						    	{field:'id',title:'商品ID',width:60,align:'center'},
						    	{field:'image',title:'商品图',width:60,align:'center',formatter:function(value,row,index){return '<img class="td-img" src="'+ value +'">';}},
								{field:'title',title:'商品名称',width:120,align:'center'},
								{field:'price',title:'价格(RMB)',width:60,align:'center'},
								{field:'description',title:'商品描述',width:120,align:'center'},
								{field:'tags',title:'标签',width:100,align:'center'},
								{field:'statusName',title:'状态',width:80,align:'center'},
								{field:'comments',title:'备注',width:100,align:'center'}
						    ]],
						    onLoadSuccess:function(){
								$(this).datagrid('enableDnd');
							}
						});
						$('#presentIdCombo').combobox({
						    url: commonConfig.shopUrlPrefix() + '/colletion/present/combobox',
						    valueField: 'id',
						    textField: 'text',
						    formatter: function(row){
								return '<img class="presentCombo-img" src="'+row.thumb+'"/><span class="item-text">'+row.text+'</span>';
							},
							onSelect: function(record){
								$('.moduleInfo .moduleInfo-images > img').attr('src' , record.thumb);
							}
						});
						$('.edit-title > a.module-banner-add').off().click(function(){
							app_module.datas.uploaderUploadCallBack = app_module.methods.moduleBannerUploadCallBack;
							$('#moduleBannerUpload').trigger('click');
						});
						$('.edit-title > a.module-banner-add-empty').off().click(function(){
							$.messager.prompt('空banner:替换文字', '', function(text){
								if (text){
									$.messager.prompt('空banner:跳转地址', '', function(location){
										$('.module-banners > ul').append('<li><img location="'+location+'" src="'+text+'" style="visibility:hidden" />'+text+'<a class="module-banner-delete"><i class="fa fa-trash-o"></i></a><div><input class="easyui-validatebox editBannerLink" placeholder="请输入跳转链接" value="'+location+'"></div></li>');
										$('.module-banners > ul >li .module-banner-delete').off().click(function(){
											$(this).parent().remove();
										});
										$('.module-banners > ul >li .editBannerLink').off().change(function(){
											var val = $(this).val()
											$(this).parent().parent().find('img').attr('location', val)
											if(!tools.testLink(val)){
												showMessage('链接格式错误···')
											}
										});
									});
								}else{
									showMessage('替换文字不得为空···')
								}
							});
						});
						$('.edit-title > a.module-product-add-aff').off().click(function(){
							$('#moduleAddProductAffWin').window('open');
							$('#module-list-monitor-datepicker').daterangepicker($.extend({} , monitorlDaterangepickerOptions, {startDate: moment().startOf('day').subtract(1, 'days'), endDate: moment().endOf('day').subtract(1, 'days')}));
							$('#moduleProductAffDatagrid').datagrid({
								height: 580,
								url: commonConfig.shopUrlPrefix() + '/monitor/product',
								queryParams: app_module.methods.getModuleProductAffDatagrQueryParams(),
								columns:[[
							    	{field:'ck',checkbox:true,align:'center'},
									{field:'product_id',title:'商品ID',width:60,align:'center'},
									{field:'title',title:'商品标题',width:120,align:'center'},
									{field:'price',title:'商品单价',width:80,align:'center'},
									{field:'image',title:'主图',width:80,align:'center',formatter: function(value,row,index){return '<img class="td-img" src="'+ value +'">';}},
									{field:'VIEW',title:'点击',width:80,align:'center'},
								]]
							});
							$('#moduleProductAffDatagrid').datagrid('clearChecked');
						});
						$('.edit-title > a.module-product-add').off().click(function(){
							$('#moduleAddProductWin').window('open');
							$('#moduleAddProductCategoryId').combotree({
							    url: commonConfig.shopUrlPrefix() + '/category/tree-list',
							    method: 'GET',
							    loadFilter: function(data,parent){
									if(data && data.code == 1){
										var treeRoot = {'text' : '全部分类', 'id': ''};
										if(data.datas.length == 0){
											return [treeRoot];
										}else{
											var _treeData = [] ; 
											$.each(data.datas, function(index , treeData) {
												var _tmpData = {
												 		id: treeData.id,
												 		text: treeData.name,
												 		attributes: {
												 			parentId: treeData.parentId,
												 			priority: treeData.priority,
												 			comments: treeData.comments
												 		}
												};
												var _tmpDataChildren = app_module.methods.findTreeChildrens(treeData);
												if(_tmpDataChildren){
													_tmpData.children = _tmpDataChildren ; 
												}
												 _treeData.push(_tmpData);
											});
											treeRoot.children = _treeData ; 
											return [treeRoot] ; 
										}
									}
									return [] ; 
								},
								onBeforeSelect: function(node){
									if(node.id && node.id != '' && node.children && node.children.length > 0) return false;
								}
							});
							$('#moduleProductDatagrid').datagrid({
								height: 580,
							    url: commonConfig.shopUrlPrefix() + '/product/list?status=10',
								idField: 'id',
							    columns:[[
							    	{field:'ck',checkbox:true,align:'center'},
									{field:'id',title:'ID',width:50,align:'center'},
									{field:'title',title:'标题',width:200,align:'center'},
									{field:'image',title:'主图',width:60,align:'center',formatter: function(value,row,index){
											return '<img class="td-img" src="'+ value +'">';
										}
									},
									{field:'description',title:'描述',width:100,align:'center'},
									{field:'tags',title:'标签',width:100,align:'center'},
									{field:'statusName',title:'状态',width:60,align:'center',formatter: function(value,row,index){
										if(value == '上线中') return '<span class="success-text">'+value+'</span>';
										if(value == '已下线') return '<span class="warning-text">'+value+'</span>';
										if(value == '创建失败') return '<span class="error-text">'+value+'</span>';
										if(value == '创建中') return '<span class="info-text">'+value+'</span>';
										if(value == '创建成功') return '<span class="primary-text">'+value+'</span>';
									}},
									{field:'sourceType',title:'来源',width:80,align:'center'},
									{field:'supplierName',title:'供应商',width:100,align:'center'},
									{field:'comments',title:'备注',width:150,align:'center'}
							    ]]
							});
							$('#moduleProductDatagrid').datagrid('clearChecked');
						});
						
						$('#moduleEditForm').form('clear');
						$('.module-banners > ul').html('');
						$('#module-banners-datagrid').datagrid("loadData", {datas:{}});
					},
					getModuleProductAffDatagrQueryParams: function(){
						var queryParams = {}
						var queryTime = $('#module-list-monitor-datepicker').val();
						queryParams.queryStartTime = queryTime.substring(0, 10);
						queryParams.momStartTime = queryTime.substring(0, 10);
						queryParams.queryEndTime = queryTime.substring(13);
						queryParams.momEndTime = queryTime.substring(13);
						queryParams.productStatus = 10;
						return queryParams;
					},
					findTreeChildrens: function(treeDatas){
						if(!treeDatas.categories || treeDatas.categories.length == 0) return null ;
						var _children = [] ;
						$.each(treeDatas.categories, function(index , _temp) {
							var childrenNode = {
								id: _temp.id,
						 		text: _temp.name,
						 		attributes: {
						 			parentId: _temp.parentId,
						 			priority: _temp.priority,
						 			comments: _temp.comments
						 		}
							};
							var _tempChildren = app_module.methods.findTreeChildrens(_temp);
							if(_tempChildren){
								childrenNode.children = _tempChildren ; 
							}
							_children.push(childrenNode);
						});
						return _children ; 
					},
					moduleBannerUploadCallBack: function(result){
						$.messager.prompt('banner地址', '跳转地址:', function(_location){
							if (_location){
								$('.module-banners > ul').append('<li><img location="'+_location+'" src="'+JSON.parse(result.response).datas[0]+'" /><a class="module-banner-delete"><i class="fa fa-trash-o"></i></a></li>');
								$('.module-banners > ul >li .module-banner-delete').off().click(function(){
									$(this).parent().remove();
								});
							}
						});
					},
	                persitsModuleProduct: function(){
	                	var _products = $('#moduleProductDatagrid').datagrid('getChecked');
	                	$('#moduleAddProductWin').window('close');
	                	if(_products.length > 0){
	                		var exsitProducts = $('#module-banners-datagrid').datagrid('getRows');
	                		
	                		$.each(_products, function(index , _product) {
	                			var _insert = app_module.methods.persitsModuleProductFilter(exsitProducts, _product) ;
	                			if(_insert && _insert != null){
	                				$('#module-banners-datagrid').datagrid('insertRow',{index: 0,row: _insert});
	                			}
	                		});
	                	}
	                	$('#module-banners-datagrid').datagrid('enableDnd');
	                },
	                persitsModuleProductFilter: function(exsitProducts , _product){
	                	var _insert = _product ; 
	                	if(exsitProducts == null || exsitProducts.length == 0) return _insert ; 
	                	$.each(exsitProducts, function(index, exsitProduct) {
	                		if(exsitProduct.id == _product.id) {
	                			_insert = null ;
	                			return false;
	                		}
	                	});
	                	return _insert ; 
	                },
					persitsModuleProductAff: function(){
						var _products = $('#moduleProductAffDatagrid').datagrid('getChecked');
	                	$('#moduleAddProductAffWin').window('close');
	                	if(_products.length > 0){
	                		$.each(_products, function(index , _product) {
								_product.id = _product.product_id
	                			$('#module-banners-datagrid').datagrid('insertRow',{index: 0,row: _product});
	                		});
	                	}
	                	$('#module-banners-datagrid').datagrid('enableDnd');
					},
					createModule: function(){
						app_module.methods.openCreateModuleWindow();
					},
					editModule: function(collectionId){
						// 在这里初始化数据
						app_module.methods.openCreateModuleWindow();
						requestServer(commonConfig.shopUrlPrefix() + '/colletion/'+collectionId, 'GET').then((response) => {
							if (response.code == 1) {
								//初始化表单
								$('#moduleEditForm').form('load' , response.datas);
								
								//初始话banner
								var _html = '' ; 
								var _values = response.datas.banners.split(';');
								$.each(_values, function(index , _value) {
									if(_value && _value.length > 0){
										var is_empty_banner = !/^\/\/[a-z0-9\/.-]*$/ig.test(_value.split('@#@')[0])
										_html += '<li><img location="'+_value.split('@#@')[1]+'" src="'+_value.split('@#@')[0]+'" '+ (is_empty_banner ? 'style="visibility:hidden"' : '') +'/>'+(is_empty_banner ? _value.split('@#@')[0] : '')+'<a class="module-banner-delete"><i class="fa fa-trash-o"></i></a><div><input class="easyui-validatebox editBannerLink" placeholder="请输入跳转链接" value="'+_value.split('@#@')[1] +'"></div></li>' ;
									}
								});
								if(_html != ''){
									$('.module-banners > ul').html(_html);
									$('.module-banners > ul >li .editBannerLink').off().change(function(){
										var val = $(this).val()
										$(this).parent().parent().find('img').attr('location', val)
									});
									$('.module-banners > ul >li .module-banner-delete').off().click(function(){
										$(this).parent().remove();
									});
								}
								$( '.module-banners').DDSort({target: 'li', floatStyle: {'border': '1px solid #ccc','background-color': '#fff'}});	
								
								
								//初始化表格
								if(response.datas.productDTOs.length > 0){
			                		// $.each(response.datas.productDTOs, function(index , productDTO) {
			                		// 	$('#module-banners-datagrid').datagrid('insertRow',{index: 0,row: productDTO});
			                		// });
									$('#module-banners-datagrid').datagrid('loadData',response.datas.productDTOs);
			                	}
			                	$('#module-banners-datagrid').datagrid('enableDnd');
								
							}else {
								$.messager.alert('提示',response.message,'error');
							}
						}).catch((error) => {
							console.log(error)
						});
						
					},
					batchEditMoudle: function(){
						var modules = $('#module-datagrid').datagrid('getChecked');
						if(modules.length == 0){
							showMessage('请选择模块···')
							return
						}
						app_module.datas.selectBatchEditIds = modules
						$('#modulesBatchParame').dialog('open');
					},
					saveBatchEditParame: function(){
						var edit_parame =  $(".batchEditModuleForm").serializeJson()
						if(!app_module.datas.selectBatchEditIds){
							return
						}
						if(edit_parame.comments == ''){
							return
						}
						var params = []
						app_module.datas.selectBatchEditIds.map(function(e){
							params.push(Object.assign({
								collectionId: e.collectionId,
							},edit_parame))
						})
						requestBodyServer(commonConfig.shopUrlPrefix() + '/colletion/comments', 'POST', params).then((response) => {
							if (response.code == 1) {
								if(response.datas && response.datas.length > 0){
									// 返回错误表
									showErrorMsgs(response.datas , [[{field:'name',title:'模块名',width:60,align:'center'},{field:'errorMsg',title:'错误信息',width:60,align:'center'}]]);
								}else{
									showMessage('<i class="fa fa-info-circle"></i>&nbsp; 批量编辑成功...');
									app_module.methods.queryDatagrid();
									$('#modulesBatchParame').dialog('close');
								}
							}else {
								$.messager.alert('提示',response.message,'error');
							}
						}).catch((error) => {
							console.log(error)
						});
					},
					batchCopyMoudle: function(){
						var modules = $('#module-datagrid').datagrid('getChecked');
						if(modules.length == 0){
							showMessage('请选择模块···')
							return
						}
						var params = []
						modules.map(function(e){
							params.push({
								collectionId: e.collectionId,
								name: e.name + ' Copy'
							})
						})
						requestBodyServer(commonConfig.shopUrlPrefix() + '/colletion/copys', 'POST', params).then((response) => {
							if (response.code == 1) {
								if(response.datas && response.datas.length > 0){
									showErrorMsgs(response.datas , [[{field:'name',title:'模块名',width:60,align:'center'},{field:'errorMsg',title:'错误信息',width:60,align:'center'}]]);
								}else{
									showMessage('<i class="fa fa-info-circle"></i>&nbsp; 批量复制成功...');
									app_module.methods.queryDatagrid();
								}
							}else {
								$.messager.alert('提示',response.message,'error');
							}
						}).catch((error) => {
							console.log(error)
						});
					},
					batchDeleteMoudle: function(){
						var modules = $('#module-datagrid').datagrid('getChecked');
						if(modules.length == 0){
							showMessage('请选择模块···')
							return
						}
						$.messager.confirm('提示', '确定删除?', function(r){
							if (r){
								var params = []
								modules.map(function(e){
									params.push(e.collectionId)
								})
								requestBodyServer(commonConfig.shopUrlPrefix() + '/colletion/batch', 'DELETE', params).then((response) => {
									if (response.code == 1) {
										showMessage('<i class="fa fa-info-circle"></i>&nbsp; 批量删除成功...');
										app_module.methods.queryDatagrid();
									}else {
										$.messager.alert('提示',response.message,'error');
									}
								}).catch((error) => {
									console.log(error)
								});
							}
						});
					},
					batchCover: function(){
						//TODO
						var modules = $('#module-datagrid').datagrid('getChecked');
						if(modules.length == 0){
							showMessage('请选择模块···')
							return
						}
						app_module.datas.uploaderUploadCallBack = app_module.methods.batchCoverCallBack;
						$('#moduleBannerUpload').trigger('click');
					},
					batchCoverCallBack: function(result){
						var imgUrl = JSON.parse(result.response).datas[0];
						var modules = $('#module-datagrid').datagrid('getChecked');
						
						var _params = {
							collectionIds: [],
							coverImg: imgUrl
						};
						
						$.each(modules, function(index, module) {
							_params.collectionIds.push(module.collectionId);
						});
						
						requestBodyServer(commonConfig.shopUrlPrefix() + '/colletion/coverImgs', 'PUT', _params).then((response) => {
							if (response.code == 1) {
								app_module.methods.queryDatagrid();
							}else {
								$.messager.alert('提示',response.message,'error');
							}
						}).catch((error) => {
							console.log(error)
						});
					},
					persitsModule: function(){
						$.messager.confirm('提示', '确定提交?', function(r){
							if (r){
								
								var _colletionDTO = $('#moduleEditForm').serializeJson();
								
								var _banners = [] ; 
								var _bannerImages = $('.module-banners > ul >li > img');
								$.each(_bannerImages , function(index , _bannerImage){
								    var _location = $(_bannerImage).attr('location') ;  
								    if(_location && _location.trim() != '' && _location.trim() != '#'){
										_banners.push($(_bannerImage).attr('src') + '@#@' + _location.trim());
								    }else{
								        _banners.push($(_bannerImage).attr('src'));
								    }
								});
								
								var _products = $('#module-banners-datagrid').datagrid('getRows');
								var _productDTOs = [] ; 
								$.each(_products , function(index , _product){
								    _productDTOs.push({id : _product.id});
								});
								
								_colletionDTO.banners = _banners.join(';');
								_colletionDTO.productDTOs = _productDTOs ; 
								
								requestBodyServer(commonConfig.shopUrlPrefix() + '/colletion/create', 'POST', _colletionDTO).then((response) => {
									if (response.code == 1) {
										$('#moduleEditWin').window('close');
										showMessage('<i class="fa fa-info-circle"></i>&nbsp; 请求成功...');
										app_module.methods.queryDatagrid();
									}else {
										$.messager.alert('提示',response.message,'error');
									}
								}).catch((error) => {
									console.log(error)
								});
							}
						});
					},
					deleteModule: function(collectionId){
						$.messager.confirm('提示', '确定删除?', function(r){
							if (r){
								requestServer(commonConfig.shopUrlPrefix() + '/colletion/' + collectionId, 'DELETE').then((response) => {
									if (response.code == 1) {
										showMessage('<i class="fa fa-info-circle"></i>&nbsp; 删除成功...');
										app_module.methods.queryDatagrid();
									}else {
										$.messager.alert('提示',response.message,'error');
									}
								}).catch((error) => {
									console.log(error)
								});
							}
						});
					},
					copyModule: function(collectionId){
						$.messager.prompt('Prompt', '模块名称:', function(collectionName){
							if (collectionName && collectionName.trim() != ''){
								requestBodyServer(commonConfig.shopUrlPrefix() + '/colletion/copy', 'POST' , {collectionId: collectionId , name: collectionName}).then((response) => {
									if (response.code == 1) {
										showMessage('<i class="fa fa-info-circle"></i>&nbsp; 创建成功...');
										app_module.methods.queryDatagrid();
									}else {
										showMessage('<i class="fa fa-info-circle"></i>&nbsp; 名称不能为空...');
									}
								}).catch((error) => {
									console.log(error)
								});
							}else{
								$.messager.alert('提示','模块名称不能为空!','error');
							}
						});
					},
					queryDatagrid: function(){
						$('#module-datagrid').datagrid('load' , $('#moduleDatagridQueryParams').serializeJson());
					},
					initUpload: function () {
	                    var uploaderUpload = new plupload.Uploader({
	                        runtimes: 'html5,html4',
	                        browse_button: 'moduleBannerUpload',
	                        url: commonConfig.shopUrlPrefix() + '/upload/image',
	                        file_data_name: 'images',
	                        filters: {
	                            max_file_size: '1024kb',
	                            mime_types: [
	                                {title : "Image files", extensions : "jpg,gif,png"}
	                            ],
	                        },
	                        multipart_params: {
	                            //access_token: utils.cookie.getCookie('accessToken')
	                        },
	                        init: {
	                            FilesAdded: function (up, files) {
	                                up.start();
	                            },
	                            FileUploaded: function(up, files, result){
	                            	app_module.datas.uploaderUploadCallBack(result);
                            	},
	                            UploadComplete: function (up, files) {
	                            },
	                            Error: function (up, err) {
	                            	$.messager.alert('提示',JSON.parse(err.response).body.message,'error');
	                            }
	                        }
	                    });
	                    uploaderUpload.init();
	                }
				},
				init : function(){
					app_module.methods.initDatagrid();
					app_module.methods.initUpload();
				}
			}
			app_module.init();
		</script>
	</body>
</html>
